import React from 'react';
import { Link } from 'react-router-dom';
import routerConfig from './routerConfig';

export default function BetterLink({to, ...rest}) {
    if (to.name && typeof to !== 'string') {
        to.pathname = getPathFormName(to.name, '', routerConfig);
        if (to.pathname === undefined) {
            throw new Error(`name属性值${to.name}无效`)
        }
    }
    return <Link {...rest} to={to} />
}


function getPathFormName(name, baseUrl, routesArr) {
    for (const item of routesArr) {
        let newPath = baseUrl + item.path;
        newPath = newPath.replace(/\/\//g, '/');
        if (item.name === name) {
            return newPath;
        } else {
            if (Array.isArray(item.children)) {
                const path = getPathFormName(name, newPath, item.children)
                if (path !== undefined) {
                    return path;
                }
            }
        }
    }
}